package com.zk.monitormanagement.utils;

import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class SDCardUtil {
	protected static final String TAG = "SDCardUtil";

	/** 判断SD卡已经挂载 */
	public static boolean cheekSDCardIsMounted() {
		return Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED);
	}

	/** 获得SD卡的根目录的绝对路径 */
	public static String getSdCardRootAbsolutePath() {
		return Environment.getExternalStorageDirectory().getAbsolutePath();
	}

	public static boolean deleteFile(File file) {
		if (!file.exists()) {
			return false;
		}
		return file.delete();
	}

	/**
	 * 删除文件
	 * 
	 * @param fileName
	 *            必须是绝对路径, sdcard0/cache/abc.mp4
	 */
	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		return deleteFile(file);
	}

	/**
	 * 获得一个文件夹的路径下面的子路径
	 * 
	 * @param path
	 *            要操作的一个文件夹的绝对路径
	 * @return List<.File> 目标文件夹的子文件、子文件夹
	 */
	public static List<File> getListForEachObjectPath(String path) {
		List<File> list;
		if (!cheekSDCardIsMounted()) {
			return null;
		}
		File fileDir = new File(path);
		File files[] = fileDir.listFiles();
		list = new ArrayList<File>();
		if (files == null) {
			return list;
		}
		for (File f : files) {
			list.add(f);
		}
		return list;
	}

	/**
	 * 保存文件
	 * 
	 * @param filePath
	 *            全路径: sdcard/cache/mainCache.bak
	 * @param append
	 *            true-追加|false-清空
	 */
	public static boolean saveFile(byte byteAry[], String filePath, boolean append) {
		FileOutputStream output = null;
		try {
			File file = new File(filePath);
			String parentStr = file.getParent();
			boolean createSDCardDir = createSDCardDir(parentStr);
			if (!createSDCardDir) {
				return false;
			}
			output = new FileOutputStream(new File(filePath), append);
			output.write(byteAry);
			output.flush();
			return true;
		} catch (Exception e) {
			Log.e("", "有异常：" + e);
		} finally {
			try {
				if (output != null) {
					output.close();
				}
			} catch (IOException e) {
				Log.e("", "有异常：" + e);
			}
		}
		return false;
	}

	public static String createFilePath(String fileName) {
		return getSdCardRootAbsolutePath() + File.separator + fileName;
	}

	/**
	 * 从SD卡中取出文件，必须是 包含SD卡根目录的，全路径 <br/>
	 * 如： sdcard0/dir/file.mp4
	 */
	public static byte[] getFile(String filePath) {
		File file = new File(filePath);
		if (!file.exists()) {
			return null;
		}
		BufferedInputStream bufIS = null;
		ByteArrayOutputStream baos = null;
		try {
			bufIS = new BufferedInputStream(new FileInputStream(file));
			baos = new ByteArrayOutputStream();
			byte buffer[] = new byte[1024 * 8];
			int len = 0;
			while ((len = bufIS.read(buffer)) != -1) {
				baos.write(buffer, 0, len);
				baos.flush();
			}
			return baos.toByteArray();
		} catch (Exception e) {
			Log.e("", "有异常: " + e);
		} finally {
			closeSrc(bufIS, baos);
		}
		return null;
	}

	/** 关闭getFileFromSDCard用到的 流 */
	private static void closeSrc(BufferedInputStream bufIS, ByteArrayOutputStream baos) {
		try {
			if (baos != null) {
				baos.close();
			}
		} catch (IOException e) {
			Log.e(TAG, "有异常: " + e);
		}
		try {
			if (bufIS != null) {
				bufIS.close();
			}
		} catch (Exception e) {
			Log.e(TAG, "有异常: " + e);
		}
	}

	public static boolean createSDCardDir(String newPath) {
		if (getSdCardRootAbsolutePath() == null) {
			Log.e("", "SD卡不可用");
			return false;
		}
		File path1 = new File(newPath);
		if (!path1.exists()) {
			boolean mkdirs = path1.mkdirs();
			return mkdirs;
		}
		return true;
	}

	public static boolean fileExist(String filePath) {
		File file = new File(filePath);
		if ((!cheekSDCardIsMounted()) || (!file.exists())) {
			return false;
		}
		return true;
	}

	/**
	 * 从SD卡中取出文件 必须是SD卡全路径 <br/>
	 * 如： sdcard0/dir/file.mp4
	 */
	public static boolean saveBitmap(Bitmap bitmap, String filePath) {
		FileOutputStream output = null;
		try {
			File file = new File(filePath);
			String parentStr = file.getParent();
			boolean createSDCardDir = createSDCardDir(parentStr);
			if (!createSDCardDir) {
				return false;
			}
			output = new FileOutputStream(new File(filePath), false);
			output.write(ImageUtil.bitMapToByte(bitmap));
			output.flush();
			return true;
		} catch (Exception e) {
			Log.e("", "有异常：" + e);
		} finally {
			try {
				if (output != null) {
					output.close();
				}
			} catch (IOException e) {
				Log.e("", "有异常：" + e);
			}
		}
		return false;
	}

	public static String getRandomFileName() {
//		String str = System.nanoTime()+ "";
////		String str = System.currentTimeMillis()+"";
//		Random random = new Random();
//		int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数
//		return "safe" + rannum + str;// 当前时间
		String str = String.valueOf(System.currentTimeMillis());
		Random random = new Random();
		int rannum = (int) (random.nextDouble() * (99999999 - 10000000 + 1)) + 10000000;// 获取8位随机数
		return "pad" + rannum + str;// 当前时间
	}
}
